<?php

namespace App\Admin\Controllers\Keyword;

use App\Admin\Actions\Keyword\ClearDerivative;
use App\Miya\Models\Area;
use App\Miya\Models\DerivativeKeyword;
use App\Miya\Models\Keyword;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class DerivativeKeywordController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '衍生关键词';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new DerivativeKeyword());
        $grid->model()->with(['main_keyword', 'area'])
            ->orderBy('type')->orderBy('id');

        $grid->column('id', '序号');
        $grid->column('keyword', '衍生词')->label();
        $grid->column('keyword_id', '主关键词')->display(function () {
            return $this->main_keyword->keyword;
        })->label();
        $grid->column('type', '类型')->display(function () {
            return DerivativeKeyword::$types[$this->type];
        })->label();
        $grid->column('area_id', '地区')->display(function () {
            return $this->area->name ?? null;
        })->label();

        $grid->filter(function (Grid\Filter $filter) {
            $filter->disableIdFilter();
            $filter->equal('keyword_id', '主关键词')->select(Keyword::pluck('keyword', 'id'));
            $filter->equal('area_id', '地区')->select(Area::pluck('name', 'id'));
            $filter->equal('type', '类型')->select(DerivativeKeyword::$types);
        });

        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new ClearDerivative());
        });

        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new DerivativeKeyword());

        $mainKeywords = Keyword::pluck('keyword', 'id');
        $areas = Area::pluck('name', 'id');

        $form->text('keyword', '衍生词')->rules(['required']);
        $form->select('keyword_id', '主关键词')->options($mainKeywords)->rules(['required']);
        $form->select('type', '类型')->options(DerivativeKeyword::$types)->rules(['required']);
        $form->select('area_id', '地区')->options($areas);

        return $form;
    }
}
